package org.example.service;

import org.python.core.Py;
import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class JythonExecutorService {

    private static final Logger logger = LoggerFactory.getLogger(JythonExecutorService.class);

    private final PythonInterpreter interpreter;

    public JythonExecutorService() {
        this.interpreter = new PythonInterpreter();
    }

    /**
     * 执行Python代码字符串
     * @param pythonCode Python代码字符串
     * @return Object 执行结果
     */
    public Object executePythonCode(String pythonCode) {
        try {
            logger.info("Executing python code: {}" , pythonCode);
            interpreter.exec(pythonCode);
            return interpreter.get("result");
        } catch (Exception e) {
            logger.error("Error executing Python code: ", e);
            throw new RuntimeException("Failed to execute Python code", e);
        }
    }

    /**
     * 执行Python函数
     */
    public Object callPythonFunction(String functionName, Object... args) {
        try {
            PyFunction function = (PyFunction) interpreter.get(functionName);
            if (function == null) {
                throw new RuntimeException("Function not found: " + functionName);
            }

            PyObject result = function.__call__(Py.javas2pys(args));
            return result.__tojava__(Object.class);

        } catch (Exception e) {
            logger.error("Error calling Python function: ", e);
            throw new RuntimeException("Failed to call Python function", e);
        }
    }

    /**
     * 加载Python脚本文件
     * @param scriptPath 脚本文件路径
     */
    public void loadPythonScript(String scriptPath) {
        try {
            interpreter.execfile(scriptPath);
        } catch (Exception e) {
            logger.error("Error loading Python script: ", e);
            throw new RuntimeException("Failed to load Python script", e);
        }
    }
}
